package com.liu.shrio02.config;

import com.liu.shrio02.model.User;
import com.liu.shrio02.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class UserRealm extends AuthorizingRealm {


    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权--->doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("user:add");
        //拿到当前登录对象
        Subject subject = SecurityUtils.getSubject();
        //拿到这个User对象，下面传入的
        User principal = (User) subject.getPrincipal();
        System.out.println(principal);
        /* 设置权限 */
        info.addStringPermission(principal.getPerms());
        //info.addRole();
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("认证--->doGetAuthenticationInfo");
        //用户名  密码
        UsernamePasswordToken usertoken = (UsernamePasswordToken) token;
        User user = userService.loginByname(usertoken.getUsername());
        if (user==null){
            return null;
        }
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("loginUser",user);
        //密码认证 shiro做
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
